package com.springcloud.filter.pre;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
@MultipartConfig
public class AuthPreZuulFilter extends ZuulFilter {

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String method = request.getMethod();
		String header = request.getHeader("content-type");
		String token = null;
		if (null != header && header.startsWith("multipart")) {
			System.err.println("这是一个multipart请求 --header:" + header);
			if (method.equals("GET")) {
				token = request.getParameter("token");
			} else {
				// post暂时获取不到参数，需要特殊处理
				// token = GetPostData.getToken(request, ctx);
				if (StringUtils.isEmpty(token)) {
					token = "post暂时获取不到参数，需要特殊处理";
				}
			}
		}
		if (StringUtils.isEmpty(token)) {
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			ctx.addZuulResponseHeader("content-type", "text/html;charset=utf-8");
			ctx.setResponseBody("name参数为空。");
			return null;
		}
		return null;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String requestURI = request.getRequestURI();
		// 放行，不拦截静态资源
		if (requestURI.endsWith(".html") || requestURI.endsWith(".jsp") || requestURI.endsWith(".js")
				|| requestURI.endsWith(".css")) {
			return false;
		}
		return true;
	}

	@Override
	public int filterOrder() {
		// 优先级，数字越大，优先级越低
		return 1001;
	}

	@Override
	public String filterType() {
		// 其他可选值还有post、error、route
		// FilterConstants.PRE_TYPE
		return "pre";
	}

}
